package Client.Component;

import Client.Util;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * LoginFrame 类，游戏登录窗口
 */
public class LoginFrame extends JFrame {
    // 用于读取存放用户账号的信息
    HashMap<String, String> info = new HashMap<>();
    public GameFrame gameFrame;

    /**
     * 构造函数，初始化登录窗口并与指定套接字关联
     *
     * @throws IOException
     */
    public LoginFrame() throws IOException {
        // 初始化窗口参数
        initFrame();

        /* 布置窗口布局 */
        LayoutFrame();

        this.setVisible(true);
    }


    /**
     * 初始化窗口的基本参数
     */
    private void initFrame() {
        this.setTitle("Login");
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setSize(new Dimension(400, 500));
        this.setLocationRelativeTo(null);
    }

    /**
     * 登录操作
     *
     * @param accountField 账号文本框
     * @param passWdField  密码文本框
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private boolean login(TextField accountField, TextField passWdField) throws IOException, ClassNotFoundException {
        String account = accountField.getText();
        String passWd = passWdField.getText();

        // 将账号密码用 LinkedList 包装发送到服务器
        LinkedList<String> userAccount = new LinkedList<>();
        userAccount.add(account);
        userAccount.add(passWd);

        Util.oos.writeObject(userAccount);
        String returned = (String) Util.ois.readObject();
        System.out.println("登录");
        System.out.println(returned.equals("true"));
        return returned.equals("true");
    }

    /**
     * 加载账号信息
     *
     * @throws IOException
     */
    private void loadingInfo() throws IOException {
        File infoFile = new File("src/res/info.txt");
        BufferedReader br = new BufferedReader(new FileReader(infoFile));
        String line;
        while ((line = br.readLine())!= null) {
            info.put(line.split("=")[0], line.split("=")[1]);
        }
    }

    /**
     * 布置窗口布局
     */
    private void LayoutFrame() {
        JPanel p = new JPanel();
        this.setContentPane(p);
        this.setLayout(null);

        // 布置登录控件
        JLabel accountText = new JLabel("账号: ");
        accountText.setBounds(70, 70, 50, 20);
        TextField accountField = new TextField();
        accountField.setBounds(150, 70, 150, 20);

        JLabel passWdText = new JLabel("密码: ");
        passWdText.setBounds(70, 100, 50, 20);
        TextField passWdField = new TextField();
        passWdField.setBounds(150, 100, 150, 20);
        passWdField.setEchoChar('*');

        JButton loginB = new JButton("登陆");
        loginB.setBounds(150, 150, 100, 25);
        loginB.addActionListener(e -> {
            try {
                Util.socket = new Socket(Util.CONNECT_IP, Util.CONNECT_PORT);
                Util.socket.setKeepAlive(true);
                System.out.println(Util.socket);
                // 输入输出流
                initStream();
                System.out.println("hi");
                if (login(accountField, passWdField)) {
                    JOptionPane.showMessageDialog(this, "登录成功;当人数足够时游戏会自动开启，请耐心等候。");
                    Util.pw.println("准备开始游戏");
                    if (Util.buf.readLine().equals("2")) {
                        JOptionPane.showMessageDialog(this, "游戏即将开始");
                        Util.pw.println("开启游戏");
                        gameFrame = new GameFrame();
                        this.setVisible(false);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "账号或密码错误，请重新登陆");
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

        p.add(accountText);
        p.add(accountField);
        p.add(passWdText);
        p.add(passWdField);
        p.add(loginB);
    }

    /**
     * 初始化输入输出流
     *
     * @throws IOException
     */
    public void initStream() throws IOException {
        Util.pw = new PrintWriter(Util.socket.getOutputStream(), true);
        Util.buf = new BufferedReader(new InputStreamReader(Util.socket.getInputStream()));
        Util.oos = new ObjectOutputStream(Util.socket.getOutputStream());
        Util.ois = new ObjectInputStream(Util.socket.getInputStream());
    }
}